<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class forgot extends CI_Controller {

	public function index()
	{
		$this->load->view('forgot');
	}

	public function check_mail()
	{
		if($this->input->post('mem_mail') != '')
		{
			$mem_mail = $this->input->post('mem_mail');
			$data = $this->forgot_model->check_mail($mem_mail);

			if($data == '')
			{
				redirect('forgot/index/error');
			} else {
				$this->gen_code($data);
				redirect('forgot/notification');		
			}

		} else {
			redirect('forgot');
		}
	}

	public function gen_code($data)
	{
		$otp_exp = date("Y-m-d H:i:s", mktime(date("H")+24, date("i")+0, date("s")+0, date("m")+0  , date("d")+0, date("Y")+0));
		$otp = rand(1000,9999);

		$input = array(
			'mem_id' => $data[0]['mem_id'],
			'otp_exp' => $otp_exp,
			'otp' => $otp
		);
		$this->forgot_model->otp($input);

		$mem_id = $data[0]['mem_id'];
		$mem_name = $data[0]['mem_name'];
		$fname = $data[0]['mem_fname'];
		$lname = $data[0]['mem_lname'];
		$ip = $_SERVER['REMOTE_ADDR'];

		$otp_link = md5(base64_encode($data[0]['mem_dateregister']*$otp));

		$message = "Dear $fname $lname<br><br>
This mail was sent because the 'forgot password' function has been applied to your account. To set a new password click the following link:<br>
".base_url()."index.php/forgot/repassword/$mem_id/$otp_link<br><br>

IP: $ip<br>
Username: $mem_name<br><br>

Regards,<br>
CS Channel Team.";

		$this->load->library('mail');
		$this->mail->send($data ,$message);
	}

	public function repassword()
	{
		$id = $this->uri->segment(3);
		$data = $this->forgot_model->get_member($id);

		$seg4 = $this->uri->segment(4);
		$otp = md5(base64_encode($data[0]['mem_dateregister']*$data[0]['otp']));

		$otp_now = date("Y-m-d H:i:s"); echo '<br>';
		$otp_exp = $data[0]['otp_exp']; echo '<br>';
		$exp = (strtotime($otp_exp) - strtotime($otp_now))/  ( 60 * 60 );

		if($exp > 0)
		{
			if($seg4 == $otp)
			{
				$id = $this->uri->segment(3);
				$data['member'] = $this->forgot_model->get_member($id);

				$this->load->view('reset_password' ,$data);
			} else {
				redirect('forgot/notification/error');
			}

		} else {
			redirect('forgot/notification/exp');
		}
		
	
	}

	public function notification()
	{
		$this->load->view('forgot_notifi');	
	}

	public function reset()
	{
		$input = array(
			'mem_id' => $this->input->post('mem_id'),
			'mem_name' => $this->input->post('mem_name'),
			'mem_pass' => md5($this->input->post('mem_pass'))
		);	

		$this->forgot_model->otp($input);

		$session['login'] = $this->authen_model->checklogin($input);
		$this->session->set_userdata($session);

		redirect();
	}
	
}